package com.mec.ServerCluser.core;

public class NetMessage {
	private String from;
	private String to;
	private ENetCommand command;
	private ENetConstance action;
	private String parameter;
	
	protected NetMessage() {
	}

	/**
	 * 用一个接收到的字符串对象化
	 * @param message
	 */
	public NetMessage(String message) {
		if (message == null) {
			return;
		}

		//定位到第一个冒号的位置
		int colonIndex = message.indexOf(':');
		int lastColonIndex;
		if (colonIndex == -1) {
			return;
		}
		from = message.substring(0, colonIndex);
		
		lastColonIndex = colonIndex+1;
		colonIndex = message.indexOf(':', lastColonIndex);
		to = message.substring(lastColonIndex, colonIndex);
		
		lastColonIndex = colonIndex+1;
		colonIndex = message.indexOf(':', lastColonIndex);
		command = ENetCommand.valueOf(message.substring(lastColonIndex, colonIndex));
		
		lastColonIndex = colonIndex+1;
		colonIndex = message.indexOf(':', lastColonIndex);
		System.out.println("解析到标准网络信息的Action时：" + message.substring(lastColonIndex, colonIndex));
		try {
			action = ENetConstance.valueOf(message.substring(lastColonIndex, colonIndex));
		} catch (IllegalArgumentException e) {
			action = null;
		}
		lastColonIndex = colonIndex+1;
		parameter = message.substring(lastColonIndex, message.length());
	}

	protected String getFrom() {
		return from;
	}

	protected NetMessage setFrom(String from) {
		this.from = from;
		return this;
	}

	protected String getTo() {
		return to;
	}

	protected NetMessage setTo(String to) {
		this.to = to;
		return this;
	}

	protected ENetCommand getCommand() {
		return command;
	}

	protected NetMessage setCommand(ENetCommand command) {
		this.command = command;
		return this;
	}

	protected ENetConstance getAction() {
		return action;
	}

	protected NetMessage setAction(ENetConstance action) {
		this.action = action;
		return this;
	}

	protected String getParameter() {
		return parameter;
	}

	protected NetMessage setParameter(String parameter) {
		this.parameter = parameter;
		return this;
	}
	
	@Override
	public String toString() {
		//使用冒号将参数分隔起来
		StringBuffer result = new StringBuffer();
		
		result.append(from).append(":")
		.append(to).append(":")
		.append(command.name()).append(":")
		.append(action == null ? "" : action).append(":")
		.append(parameter == null ? "" : parameter);

		return result.toString();
	}
	
}
